#
# OpenLookup - registry.py
#
# Copyright 2008 Ken Rimey
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import logging

from google.appengine.ext import db
from google.appengine.api import mail

cache = {}                  # map names to ClientApplication instances

class ClientApplication(db.Model):
    name = db.StringProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)

def register_client_application(name):
    def get_or_insert():
        key_name = ':' + name
        entity = ClientApplication.get_by_key_name(key_name)
        if entity:
            return entity, False
        entity = ClientApplication(key_name=key_name, name=name)
        entity.put()
        return entity, True

    if name not in cache:
        cache[name], is_new = db.run_in_transaction(get_or_insert)
        if is_new:
            notify(name)

def notify(name):
    logging.warning('Registered new client application: %s', name)
    mail.send_mail_to_admins(
        sender='ken.rimey@gmail.com',
        subject='[OpenLookup] registered new client application',
        body='Registered new client application:\n\n\t%s\n' % name)
